package lion.dev.lang;

import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Branch;
import org.dom4j.Element;
import org.dom4j.Node;

public class XMLUtil {

	@SuppressWarnings("unchecked")
	public static MapJ attributeMap(Element ele) {

		MapJ result = new MapJ();

		for (Attribute attr : (List<Attribute>) ele.attributes()) {
			result.put(attr.getName(), attr.getText());
		}

		return result;
	}

	public static MapJ attributeMap(Branch ele, String xpath) {

		return attributeMap((Element) ele.selectSingleNode(xpath));
	}

	public static String getText(Branch branch, String xpath) {

		Node node = branch.selectSingleNode(xpath);
		if (node == null) { return null; }
		return node.getText();
	}

	public static String getAttr(Branch branch, String xpath, String attr) {

		Element node = (Element) branch.selectSingleNode(xpath);
		if (node == null) { return null; }
		return node.attributeValue(attr);
	}
}
